
function hasPlayerAchievement(player, title)
	if player and getElementData(player, "player:data") and title then
		local query = exports["cmta-db"]:dbGet("SELECT * FROM `cmta_users` WHERE `id`=?", getElementData(player, "player:data").uid)
		for _, row in ipairs(query) do
			local achievements = fromJSON(row["achievements"])
			for k, v in ipairs(achievements) do
				if v[1] == title then
					return true
				end
			end
		end
	end
	return false
end

function addAchievement(player, title)
	if player and title then
		local accid = getElementData(player, "player:data").uid
		if accid and not hasPlayerAchievement(player, title) then
			local time = getRealTime()
	local hours = time.hour
	local minutes = time.minute
	local seconds = time.second

        local monthday = time.monthday
	local month = time.month
	local year = time.year

        local formattedTime = string.format("%04d-%02d-%02d %02d:%02d:%02d", year + 1900, month + 1, monthday, hours, minutes, seconds)
			local data = getElementData(player, "player:data")
			data.PO = data.PO + gAchievements[title][1]
			setElementData(player, "player:data", data)
			triggerClientEvent(player, "onPlayerAchievementGet", player, title)
			local query = exports["cmta-db"]:dbGet("SELECT * FROM `cmta_users` WHERE `id`=?", accid)
			if #query > 0 then
				local achievements = fromJSON(query[1]["achievements"])
				table.insert(achievements, {title, formattedTime})
				exports["cmta-db"]:dbSet("UPDATE `cmta_users` SET `achievements`=? WHERE `id`=?", toJSON(achievements), accid)
			end
		end
	end
end
addEvent("onPlayerAddAchievement", true)
addEventHandler("onPlayerAddAchievement", root, addAchievement)

function getPlayerAchievements(player)
	if player then
		local uid = getElementData(player, "player:data").uid or 0
		if uid then
			local query = exports["cmta-db"]:dbGet("SELECT * FROM `cmta_users` WHERE `id`=?", uid)
			if #query > 0 then
				return fromJSON(query[1]["achievements"])
			else
				return {}
			end
		end
	end
end

addCommandHandler("dajos",function(player)
	
	local uid = getElementData(player, "player:data").uid or 0
		if uid then
			local query = exports["cmta-db"]:dbGet("SELECT * FROM `cmta_users` WHERE `id`=?", uid)
			if #query > 0 then
				for i,v in pairs(fromJSON(query[1]["achievements"])) do
					outputChatBox(""..v[1]..""..v[2].."",player)
				end
			else
				return {}
			end
		end

end)

local function onPlayerWasted(totalAmmo, killer)
	if killer then
		addAchievement(source, "Pierwszy zgon")
		addAchievement(killer, "Pierwsze zabójstwo")
	end
end
addEventHandler("onPlayerWasted", root, onPlayerWasted)
